import router from './router'
import axios from 'axios'
const _import = require('./router/_import_' + process.env.NODE_ENV) //获取组件的方法
const whiteList = ['/login', '/auth-redirect'] // 不需要重定向的路有名称

var getRouter = null //用来获取后台拿到的路由

// 假装fakeRouter是通过后台接口请求回来的数据
let fakeRouter = {}

function routerGo(to, next) { //路由跳转
  getRouter = filterAsyncRouter(getRouter) //过滤路由
  router.addRoutes(getRouter) //动态添加路由
  global.antRouter = getRouter //将路由数据传递给全局变量，做侧边栏菜单渲染工作
  next({
    ...to,
    replace: true
  })
}

function saveObjArr(name, data) { //localStorage 存储数组对象的方法
  localStorage.setItem(name, JSON.stringify(data))
}

function getObjArr(name) { //localStorage 获取数组对象的方法
  return JSON.parse(window.localStorage.getItem(name));

}

function filterAsyncRouter(asyncRouterMap) { //遍历后台传来的路由字符串，转换为组件对象
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      route.component = _import(route.component)
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })

  return accessedRouters
}

router.beforeEach(async (to, from, next) => {

  //获取用户登录的token，或者其他用户信息
  const hasToken = window.localStorage.getItem('user')
  console.log(getRouter);
  if (hasToken) { //判断
    if (to.path === '/login') {
      // 如果登录过了，直接到首页
      next({
        path: '/home'
      })
    } else { //没登录走这个
      if (!getRouter) {
        //getRouter 用来获取后台拿到的路由 不加这个判断，路由会陷入死循环，不要问我为什么
        //问就是 一直routerGo，一直走判断，然后一直routerGo，一直走判断
        if (!getObjArr('router')) { //如果localStorage没router 这个字段的话
          console.log(123);
          fakeRouter = {
            "router": [{
              icon: 'el-icon-house',
              path: '/home',
              component: 'home',
              name: 'home',
              redirect: {
                name: "index"
              },
              children: [{
                icon: 'el-icon-discount',
                path: 'index',
                component: 'index',
                name: 'index',
              }, {
                icon: 'el-icon-collection',
                path: 'HW',
                component: 'HelloWorld',
                name: 'HW',
              }, {
                icon: 'el-icon-bank-card',
                path: 'item',
                component: 'item',
                name: 'item',
              }]
            }, {
              path: '/404',
              component: '404',
              name: '404',
            }, {
              path: "*",
              redirect: "/404"
            }]
          }
          getRouter = fakeRouter.router //假装模拟后台请求得到的路由数据
          //真实情况下，请求接口拿路由
          console.log(getRouter);
          saveObjArr('router', getRouter) //存储路由到localStorage

          routerGo(to, next) //执行路由跳转方法

        } else { //从localStorage拿到了路由
          console.log(456);
          getRouter = getObjArr('router') //拿到路由
          routerGo(to, next) //直接走
        }
      } else {
        console.log(789789);

        // saveObjArr('router', getRouter) //存储路由到localStorage
        next() //拿到就直接走
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) { //如果不写这个，会报什么栈溢出，反正就是死循环
      next()
    } else {
      next('/login')
    }
  }
})
